const {db} = require("../../config/dbconfig");


exports.addOrUpdateUser = async (req, res, next) => {
    const {id, username, email, password} = req.body;
    if (!username || !email || !password) {
        return res.status(400).json({error: 'Username, email, and password are required'});
    }
    if (id) {
        // 更新用户
        const sql = 'UPDATE Users SET username = ?, email = ?, password = ? WHERE id = ?';
        db.query(sql, [username, email, password, id], (error, results) => {
            if (error) {
                console.error('Error updating user:', error);
                return res.status(500).json({error: 'Error updating user'});
            }
            if (results.affectedRows === 0) {
                return res.status(404).json({error: 'User not found'});
            }
            res.json({message: 'User updated successfully'});
        });
    } else {
        // 新增用户
        const sql = 'INSERT INTO Users (username, email, password) VALUES (?, ?, ?)';
        db.query(sql, [username, email, password], (error, results) => {
            if (error) {
                console.error('Error adding user:', error);
                return res.status(500).json({error: 'Error adding user'});
            }
            res.status(201).json({code: '200', message: 'User added successfully', userId: results.insertId});
        });
    }
}
// 获取用户列表
exports.getUserList = async (req, res, next) => {
    const sql = 'SELECT * FROM Users';
    db.query(sql, (error, results) => {
        if (error) {
            console.error('Error fetching users:', error);
            return res.status(500).json({error: 'Error fetching users'});
        }
        res.json(results);
    });
}

exports.getUserById = async (req, res, next) => {
    const userId = req.params.id;
    const sql = 'SELECT id, username, email FROM Users WHERE id = ?';
    db.query(sql, [userId], (error, results) => {
        if (error) {
            console.error('Error fetching user:', error);
            return res.status(500).json({error: 'Error fetching user'});
        }
        if (results.length === 0) {
            return res.status(404).json({error: 'User not found'});
        }
        res.json(results[0]);
    });
}

exports.deleteUserByIds = async (req, res, next) => {
    const {ids} = req.body;
    if (!ids || !Array.isArray(ids) || ids.length === 0) {
        return res.status(400).json({error: 'Invalid user IDs'});
    }
    const sql = 'DELETE FROM Users WHERE id IN (?)';
    db.query(sql, [ids], (error, results) => {
        if (error) {
            console.error('Error deleting users:', error);
            return res.status(500).json({error: 'Error deleting users'});
        }
        res.json({message: 'Users deleted successfully', affectedRows: results.affectedRows});
    });
}

exports.getIP = async (req, res, next) => {
    let userIP = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
    console.log(userIP)
    res.send(userIP)
}